package com.jzsk.variable.center.common.utils;

import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author jiangli  2018/4/11
 * @version v1.0
 */
public class IpUtils {

    private static final String X_FORWARDED_FOR = "x-forwarded-for";

    private static final String PROXY_CLIENT_IP = "Proxy-Client-IP";

    private static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";

    private static final String IP_UNKNOWN = "unknown";

    private static final String IP_V4_LOCAL = "127.0.0.1";

    private static final String IP_V6_LOCAL = "0:0:0:0:0:0:0:1";

    private static final String SEPARATOR = ",";

    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader(X_FORWARDED_FOR);

        if (StrUtil.isEmpty(ipAddress) || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(PROXY_CLIENT_IP);
        }

        if (StrUtil.isEmpty(ipAddress) || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(WL_PROXY_CLIENT_IP);
        }

        if (StrUtil.isEmpty(ipAddress) || IP_UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals(IP_V4_LOCAL) || ipAddress.equals(IP_V6_LOCAL)) {
                try {
                    //根据网卡取本机配置的IP
                    InetAddress inetAddress = InetAddress.getLocalHost();
                    ipAddress = inetAddress.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }

        if (StrUtil.isNotEmpty(ipAddress) && ipAddress.length() > 15) {
            if (ipAddress.indexOf(SEPARATOR) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}